package com.englisheveryday.media;

import java.io.File;
import java.io.FileNotFoundException;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.englisheveryday.R;
import com.englisheveryday.exception.FileNotPlayException;
import com.englisheveryday.exception.FileNotSupportException;
import com.englisheveryday.utils.L;

/**
 * <pre>
 *    
 * </pre>
 * @author 马永华
 * @date 2012-9-12 下午5:15:50
 * @version 1.1
 */

public class RichMediaPlayer extends View {
	
	private Context context;
	private View view;
	private String file;
	private Handler handler;
	private TextView playTime;
	private ImageView playButtonImage;
	private SeekBar playSeekbar;
	private MediaPlayer mediaPlayer;
	private String[] supportType = new String[]{".mp3",".wav",".amr"};
	private boolean isPause;
	private boolean configureAble = false;
	private boolean seekAble = true;
	public RichMediaPlayer(Context context) {
		super(context);
		mediaPlayer = new MediaPlayer();
		this.context = context;
		this.mediaPlayer = new MediaPlayer();
		this.handler = new Handler();
		setPlayerView();
	}
	
	private void setPlayerView(){
		if(context==null){
			L.d("context为null");
			return;
		}
		LinearLayout playLinearLayout =  (LinearLayout)LayoutInflater.from(context).inflate(R.layout.rich_media_player, null);
		playButtonImage = (ImageView)playLinearLayout.findViewById(R.id.player);
		playTime = (TextView)playLinearLayout.findViewById(R.id.playtime);
		//可以在时间上点击
		playTime.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changePlayerState();
			}
		});
		//可以在播放按钮上点击
		playButtonImage.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changePlayerState();
			}
		});
		//播放进度显示
		playSeekbar = (SeekBar)playLinearLayout.findViewById(R.id.playSeekBar);
		playSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				seekTo(seekBar.getProgress());
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				handler.removeCallbacks(seekBarRefreshThread);
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				//设置播放时间
				setPlayTime(progress,getDuration());
			}
		});
		//播放完毕
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				L.d("complete");
				handler.removeCallbacks(seekBarRefreshThread);
				playSeekbar.setProgress(0);
				playButtonImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_play));
			}
		});
		//设置seekto
		mediaPlayer.setOnSeekCompleteListener(new OnSeekCompleteListener() {
			@Override
			public void onSeekComplete(MediaPlayer mp) {
				seekAble = true;
			}
		});
		view = playLinearLayout;
	}
	
	public View getView(){
		return this.view;
	}
	
	//播放
	public void play(){
		start(file);
		playButtonImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_pause));
		isPause = false;
		initSeekBarState();
		handler.post(seekBarRefreshThread);
	}
	
	//初始化进度条
	private void initSeekBarState(){
		playSeekbar.setMax(getDuration());
		playSeekbar.setProgress(getCurrentDuration());
	}
	
	
	//设置播放时间
	public void setPlayTime(int currentTime,int totalTime){
		int currentTimeSeconds =  currentTime/1000;
		int totalTimeSeconds = totalTime/1000;
		if(playTime==null)
			return;
		playTime.setText(convertTime(currentTimeSeconds/60)+":"+convertTime(currentTimeSeconds%60)+"/"+convertTime(totalTimeSeconds/60)+":"+convertTime(totalTimeSeconds%60));
	}
	
	//转换播放时间格式
	public String convertTime(int time){
		if(time<10)
			return "0"+time;
		return time+"";
	}
	
	
	//设置要播放的文件
	public void setPath(String file){
		this.file = file;
	}
	
	
	//设置进度
	Runnable seekBarRefreshThread = new Runnable(){
		@Override
		public void run() {
			//每隔1s，刷新一下进度条
			playSeekbar.setProgress(getCurrentDuration());
			handler.postDelayed(seekBarRefreshThread, 1000);
		}
	};
	
	
	//修改按钮的样式
	private void changePlayerState(){
		//没有播放，没有暂停->播放
		if(!isPlaying()&&!isPause){
			try{
				play();
				playButtonImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_pause));
			}catch(Exception e){
				e.printStackTrace();
			}
			return;
		}
		//正在播放中->暂停
		if(isPlaying()){
			pause();
			isPause = true;
			playButtonImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_play));
			return;
		}
		//正在暂停->恢复
		if(!isPlaying()&&isPause){
			restart(playSeekbar.getProgress());
			playButtonImage.setImageDrawable(getResources().getDrawable(R.drawable.ic_media_pause));
			isPause = false;
			return;
		}
	}
	
	//获得当前播放器播放状态
	public boolean isPlaying(){
		if(mediaPlayer==null) return false;
		return mediaPlayer.isPlaying();
	}
	
	//开始播放
	private void start(String path){
		try {
			if(mediaPlayer==null)
				return;
			mediaPlayer.reset();
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare();
			mediaPlayer.start();
			configureAble = true;
			L.d("playing");
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	//获得文件名的后缀
	public String suffixName(String fileName){
		if(fileName==null||"".equals(fileName)||!fileName.contains("."))
			return "";
		return fileName.substring(fileName.lastIndexOf("."));
	}
	
	//停止
	private void stop(){
		L.d("stop");
		if(mediaPlayer!=null&&mediaPlayer.isPlaying())
			mediaPlayer.stop();
		//取消更新线程
		handler.removeCallbacks(seekBarRefreshThread);
	}
	
	
	//暂停
	private void pause(){
		L.d("pause");
		if(mediaPlayer!=null&&mediaPlayer.isPlaying())
			mediaPlayer.pause();
		//取消更新线程
		handler.removeCallbacks(seekBarRefreshThread);
	}
	
	
	//重新播放
	private void restart(int duration){
		L.d("restart");
		if(mediaPlayer!=null){
			mediaPlayer.seekTo(duration);
			mediaPlayer.start();
			handler.post(seekBarRefreshThread);
		}
	}
	
	//释放
	public void release(){
		if(mediaPlayer!=null){
			if(mediaPlayer.isPlaying())
				stop();
			mediaPlayer.release();
		}
	}
	
	//跳转
	private void seekTo(int value){
		//如果正在播放
		if(mediaPlayer!=null&&mediaPlayer.isPlaying()&&seekAble){
			seekAble = false;
			L.d("seekTo:"+value);
			mediaPlayer.seekTo(value);
			handler.post(seekBarRefreshThread);
		}
	}
	
	//获得总时间（毫秒）
	private int getDuration(){
		if(mediaPlayer!=null&&configureAble){
			return mediaPlayer.getDuration();
		}
		return 0;
	}
	
	//获得当前时间（毫秒）
	private int getCurrentDuration(){
		if(mediaPlayer!=null&&mediaPlayer.isPlaying())
			return mediaPlayer.getCurrentPosition();
		return 0;
	}
}

